package com.hx.order.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hx.common.api.MiaoshaGoodsService;
import com.hx.common.api.MiaoshaUserService;
import com.hx.common.api.OrderService;
import com.hx.common.domain.Goods;
import com.hx.common.domain.MiaoshaGoods;
import com.hx.common.domain.MiaoshaUser;
import com.hx.common.domain.User;
import com.hx.common.to.OrderMessageTo;

import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


/**
 * @Author wonghiu
 * @Date 2021/6/6 10:45
 * @Version 1.0.1
 *
 * 监听秒杀服务发送的创建订单消息，进行订单创建
 */
@Slf4j
@Component
@RabbitListener(queues = "order.miaosha.order.queue")
public class OrderMiaoShaListener {
    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Reference(check = false)
    private MiaoshaUserService userService;

    @Reference(check = false)
    private MiaoshaGoodsService goodsService;

    @RabbitHandler
    @Transactional
    // 监听队列消息，异步执行订单创建
    public void listener(OrderMessageTo orderMessageTo, Channel channel, Message message) throws IOException{
        // 根据秒杀工作单获取用户信息和商品信息
        MiaoshaUser miaoshaUser = userService.getUserById(orderMessageTo.getUserId());
        MiaoshaGoods miaoshaGoods = goodsService.getGoodsById(orderMessageTo.getGoodsId());
        // 创建预订单
        orderService.createPreOrder(miaoshaUser,miaoshaGoods,orderMessageTo);
        // 远程调用才需要try
        try {
            // 锁库存
            goodsService.reduceStock(orderMessageTo);
            // TODO 会员服务
            // TODO 优惠券
            // 完成订单，等待支付
            orderService.finishPreOrder(orderMessageTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //订单创建过程一旦出现异常，则将工作单作为消息发送至callback队列，让其余回滚服务监听并回滚
            rabbitTemplate.convertAndSend("order-event-exchange","order.callback.queue",orderMessageTo);
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
